<?php

namespace App\Http\Controllers;

use App\Common\TestSync;
use App\Model\Goods;
use Illuminate\Http\Request;
use JsonRPC\Server;
use Chumper\Zipper\Zipper;

class TestController extends Controller
{
    public function testGo()
    {
        return 12345;
        \Swoole\Runtime::enableCoroutine();
        go(function ()
        {
            sleep(1);
            echo "b";
        });

        go(function ()
        {
            sleep(2);
            echo "c";
        });
    }

    public function test()
    {
        phpinfo();
    }

    public function testRpc()
    {

    }

    public function testEla(Request $request)
    {
        $result = Goods::search('中华')->get();

        return $result;
    }

    public function testZip()
    {
        //压缩
        $reduce_path = storage_path('aa.zip');//压缩后的地址
        $zipper = new Zipper();

        $arr = glob(public_path());//要压缩的文件
        $zipper->make($reduce_path)->add($arr)->close();

        return response()->download($reduce_path);
    }

    public function unzip()
    {
        $reduce_path = storage_path('aa.zip');//被解压的地址
        $reduce_path1 = storage_path('bb');//解压后的地址
        $zip = new Zipper();
        $zip->make($reduce_path)->extractTo($reduce_path1);
        dd(23445);
    }

    public function testSync(Request $request)
    {
        $file = public_path('data.txt');
        $arr = [];
        for ($i = 0; $i < 2000; $i++) {//2000个并发访问
            $request = new TestSync($file);
            $arr[$i] = $request;
            // 创建新线程，随后线程会执行 run 方法
            if (! $request->start()) {
                die("Start thread failed\n");
            }
//创建好一个线程
            $request->synchronized(function ($thread) {
                $thread->done = true;
                $thread->notify();//唤醒通知 然后让别的线程获取到锁
            }, $request);
        }

        for ($i = 0; $i < 2000; $i++) {
            // join 是阻塞的，所以脚本运行时间取决于耗时最长的线程
            if (! $arr[$i]->join()) {
                die("Join failed\n");
            }
        }
    }

    public function testImg()
    {
        dd(123);
    }
}
